const WXBizMsgCrypt = require('./wxBizMsgCrypt');
const { logger } = require('../utils/serviceLogger');
const xml2js = require('xml2js');

// 第三方发送消息给公众平台
const appId = "wxafd8ec7535068dba";
const encodingAesKey = "iC8Uwd1SM0eK4BofjQCKHUwvFD0EYIP15x3J3zIblsc";
const token = "FNT1W303PS1Z3CA87PY9RJTGRWQ1B3B8";
const pc = new WXBizMsgCrypt(token, encodingAesKey, appId);

exports.encodeMsg = (params) => {
    const xmlStr = `<xml>` +
        `<ToUserName><![CDATA[${params.originalMsg.FromUserName}]]></ToUserName>` +
        `<FromUserName><![CDATA[${params.originalMsg.ToUserName}]]></FromUserName>` +
        `<CreateTime>${params.originalMsg.CreateTime}</CreateTime>` +
        `<MsgType><![CDATA[text]]></MsgType>` +
        `<Content><![CDATA[${params.msgText}]]></Content>` + `</xml>`;
    
    const obj = pc.encryptMsg(xmlStr, params.originalMsg.CreateTime, params.nonce, '');
    if (obj.code == 0) {
        logger.info({}, {
            label: '加密成功，xml生成成功：'+ obj.encryptMsg
        } );
        return obj.encryptMsg;
    } else {
        logger.error('加密失败，xml生成失败：', JSON.stringify(obj));
    }
}

exports.decodeMsg = async (params) => {
    // 第三方收到公众号平台发送的消息
    const obj = pc.decryptMsg(params.msg_signature, params.timestamp, params.nonce, params.postData, '');
    if (obj.code == 0) {
        return new Promise((resolve, reject) => {
            xml2js.parseString(obj.msg, (err, result) => {
                console.log('xml2js result：', result.xml);
                resolve({
                    ToUserName: result.xml.ToUserName[0],
                    FromUserName: result.xml.FromUserName[0],
                    CreateTime: result.xml.CreateTime[0],
                    MsgType: result.xml.MsgType[0],
                    Content: result.xml.Content[0],
                    MsgId: result.xml.MsgId[0],
                    Event: result.xml.Event ? result.xml.Event[0] : ''
                });
            })
        });
    } else {
        logger.info({}, {
            label: '解密失败：' + obj.code
        });
    }
}

exports.xml2js = async (xmlStr) => {
    return new Promise((resolve, reject) => {
        xml2js.parseString(xmlStr, (err, result) => {
            console.log('xml2js result：', result.xml);
            resolve({
                ToUserName: result.xml.ToUserName[0],
                FromUserName: result.xml.FromUserName[0],
                CreateTime: result.xml.CreateTime[0],
                MsgType: result.xml.MsgType[0],
                Content: result.xml.Content ? result.xml.Content[0] : '',
                MsgId: result.xml.MsgId ? result.xml.MsgId[0] : '',
                Event: result.xml.Event ? result.xml.Event[0] : '',
                Encrypt: result.xml.Encrypt ? result.xml.Encrypt[0] : ''
            });
        })
    });
}

exports.resWXMsg = (params) => {
    // 生成发送的xml
    const xmlStr = `<xml>` +
        `<ToUserName><![CDATA[${params.ToUserName}]]></ToUserName>` +
        `<FromUserName><![CDATA[${params.FromUserName}]]></FromUserName>` +
        `<CreateTime>${params.CreateTime}</CreateTime>` +
        `<MsgType><![CDATA[text]]></MsgType>` +
        `<Content><![CDATA[${params.Content}]]></Content>` + `</xml>`;
    return xmlStr;
}


// const timeStamp = "1409304348";
// const nonce = "xxxxxx";
// const text = "<xml><ToUserName><![CDATA[oia2Tj我是中文jewbmiOUlr6X-1crbLOvLw]]></ToUserName><FromUserName><![CDATA[gh_7f083739789a]]></FromUserName><CreateTime>1407743423</CreateTime><MsgType><![CDATA[video]]></MsgType><Video><MediaId><![CDATA[eYJ1MbwPRJtOvIEabaxHs7TX2D-HV71s79GUxqdUkjm6Gs2Ed1KF3ulAOA9H1xG0]]></MediaId><Title><![CDATA[testCallBackReplyVideo]]></Title><Description><![CDATA[testCallBackReplyVideo]]></Description></Video></xml>";

// let encryptMsg = '';
// let errCode = pc.encryptMsg(text, timeStamp, nonce, encryptMsg);
// if (errCode === 0) {
//     console.log("加密后: " + encryptMsg);
// } else {
//     console.log(errCode);
// }

// const parser = new DOMParser();
// const xmlDoc = parser.parseFromString(encryptMsg, "text/xml");
// const encryptNode = xmlDoc.getElementsByTagName('Encrypt')[0];
// const msgSignNode = xmlDoc.getElementsByTagName('MsgSignature')[0];
// const encrypt = encryptNode.textContent;
// const msgSign = msgSignNode.textContent;

// const format = "<xml><ToUserName><![CDATA[toUser]]></ToUserName><Encrypt><![CDATA[%s]]></Encrypt></xml>";
// const fromXml = format.replace("%s", encrypt);

// // 第三方收到公众号平台发送的消息
// let msg = '';
// errCode = pc.decryptMsg(msgSign, timeStamp, nonce, fromXml, msg);
// if (errCode === 0) {
//     console.log("解密后: " + msg);
// } else {
//     console.log(errCode);
// }
